package org.example.thread.chapterIV;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 分别 不同的线程去 去获取数据库连接
 */
public class ConnectionClient {

    static int threadCount = 50;
    static ConnectionPool pool = new ConnectionPool(10);
    /**
     * 保证所有ConnectionRunner 能够同时开始。执行 countdown 。则释放所有线程
     */
    static CountDownLatch start = new CountDownLatch(1);
    static CountDownLatch end = new CountDownLatch(threadCount);

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger got = new AtomicInteger();
        AtomicInteger notGot = new AtomicInteger();
        int count = 50;
        for (int i = 0; i < threadCount; i++) {
            new Thread(new ConnectionRunner(count, got, notGot), "ConnectionRunner").start();
        }
        start.countDown();
        end.await();
        System.out.println();
        System.out.println("got" + got);
        System.out.println("notGot" + notGot);

    }

    /**
     * 获取 数据库连接
     */
    static class ConnectionRunner implements Runnable {
        int count; // 线程获取上限
        AtomicInteger got;
        AtomicInteger notGot;

        public ConnectionRunner(int count, AtomicInteger got, AtomicInteger notGot) {
            this.count = count;
            this.got = got;
            this.notGot = notGot;
        }

        @Override
        public void run() {
            try {
                start.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            while (count > 0) {
                try {
                    Connection connection = pool.getConnection(1000);
                    if (connection != null) {
                        try {
                            got.incrementAndGet();
                            connection.createStatement();
                            connection.commit();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } finally {
                            pool.releaseConnection(connection);
                        }
                    } else {
                        notGot.incrementAndGet();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }
}
